package main

import (
	"common"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/unrolled/render" //展示html的包
	"logic"
	"net/http"
	"time"
)

var (
	renderHtml *render.Render
)

func init() {
	option := render.Options{
		Directory:  "../views",                 //html路径
		Extensions: []string{".tmpl", ".html"}, //文件后缀
	}
	renderHtml = render.New(option)
}

//返回html
func handleIndex(w http.ResponseWriter, r *http.Request) {
	renderHtml.HTML(w, http.StatusOK, "index", nil)
}

//返回成功信息
func responseSuccess(w http.ResponseWriter, data interface{}) {
	m := make(map[string]interface{}, 16)
	m["code"] = 0
	m["message"] = "sucess"
	m["data"] = data

	result, err := json.Marshal(m)
	if err != nil {
		return
	}

	w.Write(result)
}

//前缀搜索API
func handlePrefixSearch(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	keyword := r.FormValue("keyword")

	start := time.Now().UnixNano()
	data := logic.PrefixSearch(keyword, 16)
	//fmt.Printf("%v", schools)

	end := time.Now().UnixNano()
	fmt.Printf("Trie树:keyword:%s result:%d cost:%d us\n", keyword, len(data), (end-start)/1000)
	responseSuccess(w, data)
}

//敏感词搜索API
func handleSearch(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	keyword := r.FormValue("keyword")
	fmt.Println("敏感词:", keyword)

	data := logic.Search(keyword)

	//fmt.Printf("%v", schools)
	responseSuccess(w, data)
}

func main() {
	//连接数据库
	db, err := gorm.Open("mysql", "root:zhangxiansen@tcp(106.12.21.94:3306)/trie?charset=utf8&parseTime=True&loc=Local")
	db.SingularTable(true)
	defer db.Close()
	if err != nil {
		fmt.Printf("数据库连接失败,原因:%s", err.Error())
	}

	//查出所有数据,加入到Trie树中
	var goodsData []common.Goods
	db.Find(&goodsData)
	//fmt.Printf("%v", goodsData)

	//加载数据文件到trie树
	if err = logic.InitGoods(goodsData); err != nil {
		panic(err.Error())
	}

	//路由
	http.HandleFunc("/index", handleIndex)                      //html页面
	http.HandleFunc("/school/prefixsearch", handlePrefixSearch) //前缀搜索接口
	http.HandleFunc("/school/search", handleSearch)             //敏感词搜索接口

	err = http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Printf("listen failed, err:%v\n", err)
		return
	}
}
